<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增物品归还记录')"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <style>
        .item-list {
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            padding: 10px;
            max-height: 300px;
            overflow-y: auto;
            margin-bottom: 15px;
        }

        .item-card {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            margin-bottom: 10px;
            transition: all 0.3s;
        }

        .item-header {
            cursor: pointer;
        }

        .item-card:hover {
            border-color: #1ab394;
            background-color: #fafafa;
        }

        .item-card.selected {
            border-color: #1ab394;
            background-color: #e8f4ff;
        }

        .item-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            margin-right: 10px;
            border-radius: 4px;
        }

        .item-info {
            flex: 1;
        }

        .item-name {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .item-details {
            font-size: 12px;
            color: #666;
        }

        .item-quantity {
            color: #ff6a6a;
            font-weight: bold;
        }

        .disabled-section {
            opacity: 0.5;
            pointer-events: none;
        }

        .item-description {
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px dashed #eee;
            font-size: 14px;
        }

        .item-form-group {
            margin-bottom: 10px;
        }
    </style>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-return-add">
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">关联租赁记录：</label>
                <div class="col-sm-8">
                    <select name="leaseId" id="leaseId" class="form-control" required>
                        <option value="">请选择</option>
                        <option th:each="leaseRecord : ${leaseRecordList}" th:value="${leaseRecord.id}"
                                th:text="${leaseRecord.orderId}"></option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 出库项目展示区域 -->
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label">出库项目：</label>
                <div class="col-sm-8">
                    <div id="itemContainer" class="item-list">
                        <div class="help-block text-center" id="itemMessage">请先选择关联租赁记录</div>
                        <!-- 物品将通过JS动态生成 -->
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">实际归还数量：</label>
                <div class="col-sm-8">
                    <input name="returnQuantity" id="returnQuantity" class="form-control" type="text" required>
                    <div class="help-block">最大可还数量：<span id="maxReturnQuantity">0</span></div>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">归还时间：</label>
                <div class="col-sm-8">
                    <div class="input-group date">
                        <input name="returnTime" class="form-control" placeholder="yyyy-MM-dd" type="text" required>
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label">验收结果描述：</label>
                <div class="col-sm-8">
                    <input name="checkResult" class="form-control" type="text">
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">是否逾期：</label>
                <div class="col-sm-8">
                    <div class="radio-box" th:each="dict : ${@dict.getType('is_overdue')}">
                        <input type="radio" th:id="${'isOverdue_' + dict.dictCode}" name="isOverdue"
                               th:value="${dict.dictValue}" th:checked="${dict.default}" required>
                        <label th:for="${'isOverdue_' + dict.dictCode}" th:text="${dict.dictLabel}"></label>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: datetimepicker-js"/>
<script th:inline="javascript">
    var prefix = ctx + "system/return"
    $("#form-return-add").validate({
        focusCleanup: true,
        rules: {
            returnQuantity: {
                required: true,
                digits: true,
                min: 1,
                max: function () {
                    return parseInt($('#maxReturnQuantity').text()) || 0;
                }
            }
        },
        messages: {
            returnQuantity: {
                required: "请输入归还数量",
                digits: "请输入有效数字",
                min: "归还数量至少为1",
                max: "归还数量不能超过出库数量"
            }
        }
    });

    function submitHandler() {
        if ($.validate.form()) {
            $.operate.save(prefix + "/add", $('#form-return-add').serialize());
        }
    }

    $("input[name='returnTime']").datetimepicker({
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true
    });

    // 封装加载租赁记录物品的函数
    function loadLeaseItems(leaseId) {
        var $itemContainer = $('#itemContainer');
        var $itemMessage = $('#itemMessage');

        // 清空物品容器
        $itemContainer.find('.item-card').remove();
        $('#maxReturnQuantity').text('0');
        $('#returnQuantity').val('');

        if (!leaseId) {
            $itemContainer.addClass('disabled-section');
            $itemMessage.text('请先选择关联租赁记录').show();
            return;
        }

        $itemContainer.removeClass('disabled-section');
        $itemMessage.text('正在加载出库项目...').show();

        // 调用后台接口获取租赁记录的项目
        $.ajax({
            url: ctx + 'system/lease/queryLeaseRecordItems',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({leaseRecordId: leaseId}),
            success: function (result) {
                $itemMessage.hide();

                // 注意：根据后台接口规范，成功时code应为200
                if (result.code === 0 && result.data && result.data.length > 0) {
                    // 遍历物品列表，构建商品项
                    $.each(result.data, function (index, item) {
                        var maxQuantity = parseInt(item.quantity) || 0;

                        var itemHtml = `
                            <div class="item-card">
                                <div class="d-flex item-header">
                                    ${item.imgUrl ?
                            `<img src="${item.imgUrl}" alt="${item.itemName}" class="item-image">` :
                            `<div class="item-image bg-light d-flex align-items-center justify-content-center">
                                            <i class="fa fa-box-open" style="font-size: 24px;"></i>
                                        </div>`
                        }
                                    <div class="item-info">
                                        <div class="item-name">${item.itemName || '未知物品'}</div>
                                        <div class="item-details">
                                            <span>出库数量: <span class="item-quantity">${item.quantity}</span></span> |
                                            <span>日租金: ¥${item.dailyRate}</span> |
                                            <span>租赁天数: ${item.days}天</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `;
                        $itemContainer.append(itemHtml);

                        // 设置最大可还数量（通常一个租赁记录只有一个项目）
                        $('#maxReturnQuantity').text(maxQuantity);
                        $("#form-return-add").find('input[name="returnQuantity"]').rules('remove', 'max');
                        $("#form-return-add").find('input[name="returnQuantity"]').rules('add', {
                            max: maxQuantity
                        });
                    });
                } else {
                    $itemMessage.text('该租赁记录没有关联的出库项目').show();
                }
            },
            error: function () {
                $itemMessage.text('获取出库项目失败，请重试').show();
            }
        });
    }

    // 页面初始化逻辑
    $(document).ready(function () {
        // 监听租赁记录下拉框变化
        $('#leaseId').change(function () {
            var leaseId = $(this).val();
            loadLeaseItems(leaseId);
        });
    });
</script>
</body>
</html>